package cn.tedu.sp06.filter;

import cn.tedu.sp01.web.util.JsonResult;
import com.netflix.discovery.util.StringUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    // pre,routing,post,error
    //
    //针对当前请求,是否要执行下面的过滤代码
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    /*
    * serviceId正在调用的目的,方法
    *
    *
    * */
    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext ctx= RequestContext.getCurrentContext();
        //从上下文对象获得 serviceId
        String serviceId =
                (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断是否是item-service的运用
        return "item-service".equals(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
       RequestContext ctx = RequestContext.getCurrentContext();
       //获得request对象
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if(StringUtils.isBlank(token)){
            //发送响应,阻止继续调用
            ctx.setSendZuulResponse(false);
            //告诉客户端返回的数据是什么类型
            ctx.addZuulResponseHeader("Conyent-Type",
                    "application/json;charset=UTF-8");

            String json = JsonResult
                    .build().code(400).msg("未登录").toString();

            ctx.setResponseBody(json);

        }
        return null;
    }
}
